/*
 * Sapphire
 *
 * Copyright (C) 2018 Florrie Haero
 * Copyright (C) 2018 eq
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 *
 */

const tmplAvatar = window.templates['avatar'];

/* Avatar colors, as CSS colors */
const AVATAR_COLORS = ['red', 'orange', 'green', 'blue', 'pink']
    .map(color => `var(--${color}-color)`);

const getAvatarURL = function(details) {
    if (details.hasIcon) {
        return window.BASE_ICON + encodeURIComponent(details.id);
    } else {
        return null;
    }
};

/* Returns hash of user as single number */
const getAvatarHash = function(details) {
    return details.id.split('').map(c => c.charCodeAt(0)).reduce((a, b) => a + b, 0);
};

window.getAvatar = function(details) {
    return tmplAvatar({
        url: getAvatarURL(details),
        initial: details.alias ? details.alias[0] : '?',
        color: AVATAR_COLORS[getAvatarHash(details) % AVATAR_COLORS.length]
    });
};
